package com.demo.quartz.controller;


import com.demo.quartz.entity.SysJob;
import com.demo.quartz.service.SysJobService;
import com.demo.quartz.util.CronUtils;
import enums.ErrorCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import result.Result;

/**
 * 调度任务信息操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/quartz")
@Api(value = "quartz" , tags = "定时任务管理")
public class SysJobController {
    @Autowired
    private SysJobService jobService;

    /**
     * 新建定时任务
     */
    @PostMapping("/job")
    @ApiOperation(value = "创建定时任务")
    public Result createJob(@RequestBody SysJob sysJob) throws SchedulerException {
        if (!CronUtils.isValid(sysJob.getCronExpression())) {
            return Result.failure(ErrorCodeEnum.SYS_ERR_CRON);
        }
        sysJob.setCreateBy("admin");
        jobService.insertJob(sysJob);
        return Result.success();
    }


    /**
     * 运行定时任务
     */
    @GetMapping("/run/{id}")
    @ApiOperation(value = "运行定时任务")
    public Result runJob(@PathVariable Long id) throws SchedulerException {
        jobService.run(id);
        return Result.success();
    }
}
